import { defineStore } from "pinia";

//导入request
import { reqUserLogin, reqUserInfo, reqUserLogout } from "@/api/user";
import type { loginForm, loginSuccessType } from "@/api/user/type";
import type { UserStatue } from "@/store/module/types/type";
import { set_token, get_token, remove_token } from "@/utils/tokenUtil";
import { constRouter } from "@/router/router";

export const userStore = defineStore("User", {
  state: (): UserStatue => {
    return {
      //token
      token: get_token(),
      //左侧菜单数组
      menuRoutes: constRouter,
      username: "",
      avatar: "",
    };
  },
  getters: {},
  // 封装通用化处理操作
  actions: {
    async userLogin(data: loginForm) {
      let res: loginSuccessType = await reqUserLogin(data);
      //状态判断
      // 成功以后存储当前用户的token
      if (res.code == 200) {
        //本地化处理
        set_token(res.data as string);
        this.token = res.data as string;

        let result = await reqUserInfo();
        if (result) {
          this.username = result.data.userName;
          this.avatar = result.data.icon;
        }
        return "success";
      } else {
        return Promise.reject(new Error(res.mess));
      }
    },
    async userLogout() {
      //退出用户个人信息。清除个人痕迹
      this.token = "";
      this.username = "";
      this.avatar = "";
      //去掉用户的令牌
      remove_token();
    },
  },
});
